package ynu.edu.order.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import ynu.edu.common.exception.BusinessException;
import ynu.edu.order.util.JwtUtil;

/**
 * JWT拦截器
 */
@Component
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 从请求头中获取token
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            try {
                // 验证token
                jwtUtil.validateToken(token);
                
                // 判断token类型（用户token或商家token）
                try {
                    // 尝试获取用户ID
                    Long userId = jwtUtil.getUserIdFromToken(token);
                    request.setAttribute("userId", userId);
                    request.setAttribute("tokenType", "user");
                } catch (Exception e) {
                    try {
                        // 尝试获取商家ID
                        Long merchantId = jwtUtil.getMerchantIdFromToken(token);
                        request.setAttribute("merchantId", merchantId);
                        request.setAttribute("tokenType", "merchant");
                    } catch (Exception ex) {
                        throw new BusinessException("无效的token格式");
                    }
                }
                
                return true;
            } catch (Exception e) {
                throw new BusinessException("无效的token");
            }
        }
        throw new BusinessException("请先登录");
    }
} 